package com.hong.spring.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * @author: csh
 * @Date: 2021/1/19 10:54
 * @Description:
 */
public class NettyHttpHandler extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if(msg instanceof HttpRequest) {
            //1.打印浏览器的请求地址
            System.out.println("客户端地址：" + ctx.channel().remoteAddress());

            //2.给浏览器发送的信息，封装成ByteBuf
            ByteBuf content = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8);

            //3.构造一个http的相应，即 httpresponse
            FullHttpResponse response = new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK,
                    content);
            //4.设置响应头信息-响应格式
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            //5.设置响应头信息-响应数据长度
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

            //6.将构建好 response返回
            ctx.writeAndFlush(response);
        }
    }
}
